<template>
  <el-dialog
    v-model="dialog"
    append-to-body
    :modal="mergedDialogConfig.dialogModal"
    :close-on-click-modal="mergedDialogConfig.dialogClickModalClose"
    :close-on-press-escape="mergedDialogConfig.dialogESCModalClose"
    :draggable="mergedDialogConfig.dialogDraggable"
    :show-close="mergedDialogConfig.dialogShowClose"
    :title="mergedDialogConfig.dialogTitle"
    :width="mergedDialogConfig.dialogWidth"
    :top="mergedDialogConfig.dialogTop"
    :align-center="mergedDialogConfig.dialogAlignCenter"
    :center="mergedDialogConfig.dialogContentCenter"
    :before-close="handleCancel"
    @open="handleOpen"
    @close="handleClose"
  >
    <slot name="content" />
    <slot name="tip" />
    <template v-if="mergedDialogConfig.dialogFooterBtn" #footer>
      <div class="dialog-font">
        <el-button type="info" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  defineOptions({ name: 'DiaLog' })
  import { DialogConfig } from '@/types/config'
  import { mergeConfig } from '@/utils/configMerge'
  import { ref, watch, computed } from 'vue'
  // props 定义
  interface Props {
    visible: boolean
    dialogConfig?: Partial<DialogConfig>
    done?: () => void
  }

  // 默认配置
  const defaultDialogConfig: DialogConfig = {
    dialogTitle: '默认标题',
    dialogWidth: '40%',
    dialogTop: '15vh',
    dialogShowClose: true,
    dialogModal: true,
    dialogAlignCenter: true,
    dialogContentCenter: true,
    dialogFullscreen: false,
    dialogClickModalClose: false,
    dialogESCModalClose: false,
    dialogDraggable: true,
    dialogFooterBtn: true,
  }

  const props = withDefaults(defineProps<Props>(), {
    visible: false,
    dialogConfig: () => ({}),
    done: () => void 0,
  })

  // 合并默认配置和传入的配置
  const mergedDialogConfig = computed(() => {
    return mergeConfig(defaultDialogConfig, props.dialogConfig)
  })
  const emits = defineEmits<{
    (e: 'update:visible', val: boolean): void
    (e: 'save', val: boolean): void
    (e: 'cancellation', val: boolean): void
    (e: 'open', val: boolean): void
    (e: 'close', val: boolean): void
  }>()
  const dialog = ref<boolean>(props.visible)
  // 接收 visible -> 控制内部 dialog 显隐
  watch(
    () => props.visible,
    (val) => {
      dialog.value = val
    },
    { immediate: true },
  )
  // 控制 dialog -> 通知父组件更新 visible
  watch(dialog, (val) => {
    emits('update:visible', val)
  })

  // 事件回调
  const handleSave = () => emits('save', false)
  const handleOpen = () => emits('open', true)
  const handleClose = () => emits('close', false)

  //事件
  const handleCancel = (done: () => void) => {
    props.done()
    emits('cancellation', false)
    // catch error
  }
</script>

<style scoped lang="scss">
  .pagination-container {
    background: #fff;
    padding: 32px 16px;
  }
</style>
